package com.limh.jkzs.fragment.blue

import android.text.method.ScrollingMovementMethod
import android.view.View
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import com.limh.blehelper.Ble2Manager
import com.limh.blehelper.event.BlueValue
import com.limh.blehelper.utils.DataUtils
import com.limh.jkzs.R
import com.limh.jkzs.base.BaseFragment
import com.limh.jkzs.util.Logs
import kotlinx.android.synthetic.main.fragment_serial.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import rx.Observable
import rx.Subscription
import rx.functions.Func1
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit

/**
 * Function:
 * author: limh
 * time:2018/1/17
 */
class SerialFragment : BaseFragment(), View.OnClickListener {

    private lateinit var btnClearCount: TextView
    private lateinit var btnRxClear: TextView
    private lateinit var txtRxCount: TextView
    private lateinit var txtTxCount: TextView
    private lateinit var txtReceive: TextView
    private lateinit var btnTxSend: TextView
    private lateinit var checkTxAuto: CheckBox
    private lateinit var imageMsReduce: ImageView
    private lateinit var imageMsAdd: ImageView
    private lateinit var txtMs: TextView

    private var countRx = 0
    private var countTx = 0
    private var period: Long = 1000
    private var subscribe: Subscription? = null

    override fun findView(): Int {
        return R.layout.fragment_serial
    }

    override fun initView(view: View) {
        btnClearCount = view.findViewById(R.id.btnClearCount)
        btnRxClear = view.findViewById(R.id.btnRxClear)
        txtRxCount = view.findViewById(R.id.txtRxCount)
        txtTxCount = view.findViewById(R.id.txtTxCount)
        txtReceive = view.findViewById(R.id.txtReceive)
        btnTxSend = view.findViewById(R.id.btnTxSend)
        checkTxAuto = view.findViewById(R.id.checkTxAuto)
        imageMsReduce = view.findViewById(R.id.imageMsReduce)
        imageMsAdd = view.findViewById(R.id.imageMsAdd)
        txtMs = view.findViewById(R.id.txtMs)

        txtReceive.movementMethod = ScrollingMovementMethod()
        btnClearCount.setOnClickListener(this)
        btnRxClear.setOnClickListener(this)
        btnTxSend.setOnClickListener(this)
        imageMsReduce.setOnClickListener(this)
        imageMsAdd.setOnClickListener(this)

        checkTxAuto.setOnCheckedChangeListener { _, b ->
            if (b) {
                if (null != Ble2Manager.getInstance().currentDevice) {
                    autoSend(period)
                } else {
                    showShort("请先连接蓝牙")
                    checkTxAuto.isChecked = false
                }
            } else {
                if (null != subscribe && !subscribe!!.isUnsubscribed) {
                    subscribe!!.unsubscribe()
                    subscribe = null
                }
            }
        }
        EventBus.getDefault().register(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onBlueValue(blueValue: BlueValue) {
        val bytes = blueValue.data
        countRx += bytes!!.size
        txtRxCount.text = String.format("%s", countRx)
        val str: String = if (checkRx16.isChecked) {
            DataUtils.formatHexString(bytes, true)
        } else {
            String(bytes.copyOf(), charset = Charset.forName("UTF-8"))
        }
        if (checkRxAuto.isChecked)
            txtReceive.append(str + " \r\n")
        else
            txtReceive.append(str + " ")
        //当行数大于显示区高度的时候自动滚动到底部
        val offset = txtReceive.lineCount * txtReceive.lineHeight
        if (offset > txtReceive.height) {
            txtReceive.scrollTo(0, offset - txtReceive.height + txtReceive.lineHeight)
        }
    }

    override fun onClick(p0: View?) {
        when (p0!!.id) {
            R.id.btnClearCount -> {
                countRx = 0
                countTx = 0
                txtRxCount.text = String.format("%s", countRx)
                txtTxCount.text = String.format("%s", countTx)
            }
            R.id.btnRxClear -> {
                txtReceive.text = ""
            }
            R.id.btnTxSend -> {
                sendData()
            }
            R.id.imageMsReduce -> {
                if (period > 500)
                    period -= 500
                if (period == 500.toLong()) {
                    period = 500
                }
                txtMs.text = String.format("%s", period)
                autoSend(period)
            }
            R.id.imageMsAdd -> {
                period += 500
                txtMs.text = String.format("%s", period)
                autoSend(period)
            }
        }
    }

    private fun autoSend(period: Long) {
        if (null != subscribe && !subscribe!!.isUnsubscribed) {
            subscribe!!.unsubscribe()
            subscribe = null
        }
        subscribe = Observable.interval(period, TimeUnit.MILLISECONDS)
                .takeUntil(Func1 {
                    return@Func1 !checkTxAuto.isChecked
                })
                .subscribe({
                    sendData()
                })
    }

    /**
     * 发送数据
     */
    private fun sendData() {
        val send = editTx.text.toString().trim()
        Logs.d("发送数据--->" + send)
        countTx += if (checkTxHex.isChecked) {
            Ble2Manager.getInstance().sendByHex(DataUtils.hexStringToBytes(send))
            DataUtils.hexStringToBytes(send).size
        } else {
            Ble2Manager.getInstance().sendByStr(send)
            send.length
        }
        txtTxCount.text = String.format("%s", countTx)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (null != subscribe && !subscribe!!.isUnsubscribed) {
            subscribe!!.unsubscribe()
            subscribe = null
        }
        EventBus.getDefault().unregister(this)
    }
}